package cn.edu.cdut.service;

import cn.edu.cdut.dao.AdminInfoDao;
import cn.edu.cdut.dao.StudentInfoDao;
import cn.edu.cdut.dto.MyRes;
import cn.edu.cdut.dto.PasswordChange;
import cn.edu.cdut.model.AdminInfo;
import cn.edu.cdut.model.StudentInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * Author  kobe
 * Created on 2017-06-26-22:19
 */
@Service
public class ChangePassService {

        @Autowired
        private StudentInfoDao studentInfoDao;

        @Autowired
        private AdminInfoDao adminInfoDao;

        //修改密码
        @Transactional
        public MyRes changePassword(PasswordChange passwordChange) {

                if (passwordChange.getUserId().contains("admin")) {/*根据教职工号与学号的差别进行判断，这里只是个例子*/
                        AdminInfo adminInfo = adminInfoDao.findByAdminId(passwordChange.getUserId());
                        if (!Objects.equals(adminInfo.getPassword(), passwordChange.getOldPass())) {
                                return new MyRes(201, "原密码不正确！", null);
                        } else {
                                adminInfo.setPassword(passwordChange.getNewPass());
                                adminInfoDao.save(adminInfo);
                                return new MyRes(200, "修改成功！", null);
                        }
                } else {
                        StudentInfo studentInfo = studentInfoDao.findByStuId(passwordChange.getUserId());
                        if (!Objects.equals(studentInfo.getPassword(), passwordChange.getOldPass())) {
                                return new MyRes(202, "原密码不正确！", null);
                        } else {
                                studentInfo.setPassword(passwordChange.getNewPass());
                                studentInfoDao.save(studentInfo);
                                return new MyRes(200, "修改成功！", null);
                        }
                }
        }

        //重置密码
        @Transactional
        public MyRes resetPassword(String userId) {
                StudentInfo studentInfo = studentInfoDao.findByStuId(userId);
                studentInfo.setPassword("123456");
                studentInfoDao.save(studentInfo);
                return new MyRes(200, "修改成功！", null);
        }
}
